import { ConfigEnv, loadEnv, UserConfigExport } from "vite";
import vue from "@vitejs/plugin-vue";
import qiankun from "vite-plugin-qiankun";
import importToCDN from "vite-plugin-cdn-import";
import { resolve } from "path";
import { cdnConfig } from "../cdnConfig";

export default ({ mode }: ConfigEnv): UserConfigExport => {
  return {
    base: loadEnv(mode, process.cwd()).VITE_APP_PUBLIC_PATH,
    plugins: [
      vue(),
      importToCDN({
        modules: cdnConfig,
      }),
      qiankun("vue app", {
        useDevMode: true,
      }),
    ],
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
    },
    server: {
      port: 40000,
      headers: {
        "Access-Control-Allow-Origin": "*", // 设置跨域
      },
    },
    build: {
      sourcemap: mode === "development",
      target: "esnext",
      minify: "terser", // 混淆器，terser构建后文件体积更小
      terserOptions: {
        compress: {
          // 生产环境时移除console.log()
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            // node_modules 下文件分包
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
          chunkFileNames: "vendors/[name]-[hash].js", // 三方库文件
          entryFileNames: "js/[name]-[hash].js", // entry js文件
          assetFileNames: "[ext]/[name]-[hash].[ext]", // css文件
        },
      },
    },
  };
};
